package lexical.domain;

import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;

/**
 * Symbol table class
 * 
 * @author Boghy
 * 
 */
public class ST {
	Map<Integer, String> map;
	Integer lastPosition;

	public ST() {
		map = new HashMap<Integer, String>();
		lastPosition = -1;
	}

	/**
	 * Tries to add a symbol in the symbol table. If the symbol exists in the
	 * symbol table, the symbol table will not be altered.
	 * 
	 * @param symbol
	 *            the symbol we are trying to add
	 * @return returns the position of the symbol in the symbol table
	 */
	public int add(String symbol) {
		if (map.containsValue(symbol)) {
			Set<Entry<Integer, String>> entries = map.entrySet();
			for (Entry<Integer, String> entry : entries) {
				if (entry.getValue().equals(symbol))
					return entry.getKey();
			}
		}
		lastPosition++;
		map.put(lastPosition, symbol);
		return lastPosition;
	}

	/**
	 * Returns the symbol at the given position
	 * 
	 * @param position
	 * @return the symbol or null if there is no symbol at the given position
	 */
	public String get(Integer position) {
		return map.get(position);
	}

	public void print(PrintStream printer) {
		printer.println("#################################################");
		printer.println("############### Symbol table - ST ###############");
		printer.println("#################################################");
		printer.println(" Position | Symbol");
		printer.println();
		Set<Integer> positions = new TreeSet<Integer>(map.keySet());
		for (Integer pos : positions) {
			printer.println(String.format("%10d|%10s", pos, map.get(pos)));
		}
	}

}
